<?php

namespace app\api\controller;

use app\common\controller\Api;

use app\admin\model\game\Admin as AdminModel;
use app\admin\model\game\Record as RecordModel;
use think\Db;

/**
 * 示例接口
 */
class Admin extends Api
{


    // 无需登录的接口,*表示全部
    protected $noNeedLogin = ['login','exchange','getExchangeData'];
    // 无需鉴权的接口,*表示全部
    protected $noNeedRight = ['*'];

    // 管理员加密
    protected $slat = "asdfghjkl";

    public function login()
    {
        $username = $this->request->post('username');
        $password = $this->request->post('password');
        $admin = AdminModel::get(['username' => $username]);
        if (!$admin) {
            $this->error('用户不存在');
        }

        if ($admin->status != 1) {
            $this->error('用户被禁用');
        }

        if ($admin->password !== md5($password . $this->slat)) {
            $this->error('密码错误');
        }
        $token = $this->request->token('__token__', 'sha1');

        $this->success('登录成功', ['token' => $token,'admin_name'=>$admin["name"],'admin_id'=>$admin["id"]]);
    }

    // 核销验证码
    public function exchange()
    {
        $code = $this->request->post('code');
        $admin_id = $this->request->post('admin_id');
        if (!$code) {
            $this->error('请输入核销码');
        }
        if (!$admin_id) {
            $this->error('请登录');
        }

        // 核销码格式为openid-prize_id
        if (strpos($code, '-') === false) {
            $this->error('核销码错误');
        }

        $code_split = explode('-', $code);
        $openid = $code_split[0];
        $prize_id = $code_split[1];
        if (!$openid || !$prize_id) {
            $this->error('核销码错误');
        }

        $record = RecordModel::where("openid", $openid)->where("record.id", $prize_id)->with(["prize"])->find();
        if (!$record) {
            $this->error('未找到中奖记录');
        }
        // 判断是否已经核销
        if ($record->status == 1) {
            $this->error('该奖品二维码已经核销',$record);
        }
        Db::startTrans();
        try {
            $record->status = 1;
            $record->admin_id = $admin_id;
            $record->save();
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('核销失败',$record);
        }

        $this->success('奖品核销成功',$record);
    }

    public function getExchangeData()
    {
        $admin_id = $this->request->post('admin_id');
        $recordModel = new RecordModel();
        $datas = $recordModel->getExchangeDatas($admin_id);
        $this->success('获取成功', $datas);
    }
}
